## setting up fire scar data in monthly x y tables that match climate grids.

####Load the libraries

#list the libraries needed
necessary=c("geoR", "caTools", "sp", "rgdal", "adehabitat", "maptools")

#check if library is installed
installed = necessary %in% installed.packages()
#if library is not installed, install it
if (length(necessary[!installed]) >=1) install.packages(necessary[!installed], dep = T)

#load the libraries
for (lib in necessary) library(lib,character.only=T)
    
##set the working directory

setwd ("C:/pyrogeography/DATA/")

outdir = ("C:/pyrogeography/DATA/")

#read in the fire scars and associated firescar data

FS0409 = read.csv ( "fireDATA.csv")
FS0409 [1:10,]   # look at the data
 
# create a data frame for 09 and convert signed 8 bit value to month.

FS09 = data.frame(FS0409$lat, FS0409$lon, FS0409$fs2009)
names(FS09) = c("lat", "lon", "grid")
FS09 [1:10,] # look at the data 

FS09$month = ifelse (FS09$grid > 0 & FS09$grid < 9, 1, NA) or (
FS09$month = ifelse (FS09$grid > 8 & FS09$grid < 17, 2, FS09$grid)
FS09$month = ifelse (FS09$grid > 16 & FS09$grid < 25, 3, FS09$grid)
FS09$month = ifelse (FS09$grid > 24 & FS09$grid < 37, 4, FS09$grid)
FS09$month = ifelse (FS09$grid > 36 & FS09$grid < 56, 5, FS09$grid)
FS09$month = ifelse (FS09$grid > 55 & FS09$grid < 86, 6, FS09$grid)
FS09$month = ifelse (FS09$grid > 85 & FS09$grid < 116, 7, FS09$grid)
FS09$month = ifelse (FS09$grid > 115 & FS09$grid < 146, 8, FS09$grid)
FS09$month = ifelse (FS09$grid > 145 & FS09$grid < 176, 9, FS09$grid)
FS09$month = ifelse (FS09$grid > 175 & FS09$grid < 206, 10, FS09$grid)
FS09$month = ifelse (FS09$grid > 205 & FS09$grid < 232, 11, FS09$grid)
FS09$month = ifelse (FS09$grid > 231 & FS09$grid < 255, 12, FS09$grid)
FS09$month = ifelse (FS09$grid == 255, 5, NA)

FS09[1:10,]

list(FS09)
## January 09


FSJan09 [1:10,]
FSJan09$month = ifelse (FSJan09$FS0409.fs2009 < 9, 1, NA)      #replace the raster value with the month
FSJan09 [1:10,]      # see if it worked

## February 09
FSFeb09 = subset(FS09, FS0409.fs2009 > 8 & FS0409.fs2009 < 17)  
FSFeb09$month = ifelse (FSFeb09$FS0409.fs2009 > 8 & FSFeb09$FS0409.fs2009 < 17, 2, NA)    
FSFeb09 [1:10,]      # see if it worked

## March 09

FSmar09 = subset(FS09, FS0409.fs2009 > 16 & FS0409.fs2009 < 25)  
FSmar09$month = ifelse (FSmar09$FS0409.fs2009 > 16 & FSmar09$FS0409.fs2009 < 25, 3, NA)    
FSmar09 [1:10,]      # see if it worked

## April 09

FSapr09 = subset(FS09, FS0409.fs2009 > 24 & FS0409.fs2009 < 37)  
FSapr09$month = ifelse (FSapr09$FS0409.fs2009 > 24 & FSapr09$FS0409.fs2009 < 37, 4, NA)    
FSapr09 [1:10,]      # see if it worked

## May 09

FSapr09 = subset(FS09, FS0409.fs2009 > 24 & FS0409.fs2009 < 37)  
FSapr09$month = ifelse (FSapr09$FS0409.fs2009 > 24 & FSapr09$FS0409.fs2009 < 37, 4, NA)    
FSapr09 [1:10,]      # see if it worked